package com.c201801020208.ybl.User.Activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.DialogInterface;

import android.content.Intent;

import android.os.Bundle;

import android.text.Editable;

import android.text.TextUtils;

import android.text.TextWatcher;

import android.util.Log;
import android.view.KeyEvent;

import android.view.LayoutInflater;

import android.view.MotionEvent;

import android.view.View;

import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;

import android.widget.EditText;

import android.widget.ImageView;

import android.widget.LinearLayout;

import android.widget.TextView;

import android.widget.Toast;

import com.c201801020208.ybl.Company.Activity.JobInfoActivity;
import com.c201801020208.ybl.R;
import com.c201801020208.ybl.Tables.CompanyInfo;
import com.c201801020208.ybl.Tables.MyJobInfo;
import com.c201801020208.ybl.Tool.KeyBoardUtil;
import com.c201801020208.ybl.Tool.StorageListSPUtils;
import com.c201801020208.ybl.User.FlowLayout;

import java.util.ArrayList;

import java.util.List;

import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

public class SearchActivity extends AppCompatActivity implements TextView.OnEditorActionListener, View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    private TextView textView;
    private TextView textView2;
    private EditText mSearchHeaderTv;
    private ImageView imageView;
    private ImageView mSearchDeleteHistory;
    private LinearLayout mSearchListLayout;
    private FlowLayout mSearchHistoryFl;
    private RecyclerView recyclerView;
    private SearchRecyclerViewAdapter adapter;
    public static String searchname;
    //haredPreferences 存取 搜索历史 的标签
    private static final String TAG_SEARCH_HISTORY = "tagSearchHistory";
    // 默认最多展示的搜索历史数
    // 这里只展示10个搜索历史，根据需要修改为你自己想要的数值
    private static final int DEFAULT_SEARCH_HISTORY_COUNT = 10;
    // 搜索历史
    private List<String> mSearchHistoryLists;
    // 存储 搜索历史集合 的工具类
    private StorageListSPUtils mStorageListSPUtils;


    List<CompanyInfo> mList = new ArrayList<>();
    private SearchRecyclerViewAdapter searchRecyclerViewAdapter = new SearchRecyclerViewAdapter();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        textView = findViewById(R.id.textView23);
        textView2 = findViewById(R.id.textView);
        mSearchHeaderTv = findViewById(R.id.editText2);
        imageView = findViewById(R.id.delete);
        mSearchDeleteHistory = findViewById(R.id.imageView9);
        mSearchListLayout = findViewById(R.id.ssearch);
        mSearchHistoryFl = findViewById(R.id.search_history_fl);
        recyclerView = findViewById(R.id.recy);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(searchRecyclerViewAdapter);
        searchRecyclerViewAdapter.notifyDataSetChanged();


        // 初始化
        init();
        initListener();
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 初始化搜索历史布局
        initView();
    }

    public static String getUsername() {
        return searchname;
    }

    private void initView() {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        mSearchHistoryLists = mStorageListSPUtils.loadDataList(TAG_SEARCH_HISTORY);
        if (mSearchHistoryLists.size() != 0) {
            mSearchListLayout.setVisibility(View.VISIBLE);
            for (int i = mSearchHistoryLists.size() - 1; i >= 0; i--) {
                TextView textView = (TextView) layoutInflater.inflate(R.layout.search_history_tv, mSearchHistoryFl, false);
                final String historyStr = mSearchHistoryLists.get(i);
                searchname = historyStr;
                textView.setText(historyStr);
                // 设置搜索历史的回显
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mSearchHeaderTv.setText(historyStr);
                        mSearchHeaderTv.setSelection(historyStr.length());
                    }
                });
                // FlowLayout 中添加 搜索历史
                mSearchHistoryFl.addView(textView);
            }
        }
    }

    /**
     * EditText 编辑完成点击软键盘搜索后的监听事件
     */
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (v.getId() == R.id.editText2) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                // 存取 SharedPreferences 中存储的搜索历史并做相应的处理
                processAction();
                // 点击软件盘搜索后，隐藏软键盘
                if (null != getCurrentFocus()) {
                    KeyBoardUtil.hideKeyboard(getCurrentFocus(), SearchActivity.this);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 存取 SharedPreferences 中存储的搜索历史并做相应的处理
     */
    private void processAction() {
        // 获取 EditText 输入内容
        String searchInput = mSearchHeaderTv.getText().toString().trim();
        if (TextUtils.isEmpty(searchInput)) {
            Toast.makeText(this, getResources().getString(R.string.app_search_input_empty), Toast.LENGTH_SHORT).show();
        } else {
            // 先获取之前已经存储的搜索历史
            List<String> previousLists = mStorageListSPUtils.loadDataList(TAG_SEARCH_HISTORY);
            if (previousLists.size() != 0) {
                // 如果之前有搜索历史，则添加
                mSearchHistoryLists.clear();
                mSearchHistoryLists.addAll(previousLists);
            }
            // 去除重复，如果搜索历史中已经存在则remove，然后添加到后面
            if (!mSearchHistoryLists.contains(searchInput)) {
                // 如果搜索历史超过设定的默认个数，去掉最先添加的，并把新的添加到最后
                // 这里只展示10个搜索历史，根据需要修改为你自己想要的数值
                if (mSearchHistoryLists.size() >= DEFAULT_SEARCH_HISTORY_COUNT) {
                    mSearchHistoryLists.remove(0);
                    mSearchHistoryLists.add(mSearchHistoryLists.size(), searchInput);
                } else {
                    mSearchHistoryLists.add(searchInput);
                }
            } else {
                // 如果搜索历史已存在，找到其所在的下标值
                int inputIndex = -1;
                for (int i = 0; i < mSearchHistoryLists.size(); i++) {
                    if (searchInput.equals(mSearchHistoryLists.get(i))) {
                        inputIndex = i;
                    }
                }
                // 如果搜索历史已存在，先从 List 集合中移除再添加到集合的最后
                mSearchHistoryLists.remove(inputIndex);
                mSearchHistoryLists.add(mSearchHistoryLists.size(), searchInput);
            }
            // 存储新的搜索历史到 SharedPreferences
            mStorageListSPUtils.saveDataList(TAG_SEARCH_HISTORY, mSearchHistoryLists);
            Toast.makeText(this, getResources().getString(R.string.app_search_input) + searchInput, Toast.LENGTH_SHORT).show();


            BmobQuery<CompanyInfo> categoryBmobQuery = new BmobQuery<>();
            categoryBmobQuery.addWhereEqualTo("Jobname", mSearchHeaderTv.getText().toString().trim());
            categoryBmobQuery.findObjects(new FindListener<CompanyInfo>() {
                @Override
                public void done(List<CompanyInfo> object, BmobException e) {
                    if (object.size() != 0) {
                        if (e == null) {
                            Toast.makeText(SearchActivity.this, "查询成功：", Toast.LENGTH_LONG).show();
                            for (int i = 0; i < object.size(); i++) {
                                CompanyInfo companyInfo = new CompanyInfo();
                                companyInfo.setUsername(object.get(i).getUsername());
                                companyInfo.setAddress(object.get(i).getAddress());
                                companyInfo.setWorktime(object.get(i).getWorktime());
                                companyInfo.setWorkexperience(object.get(i).getWorkexperience());
                                companyInfo.setCompanyname(object.get(i).getCompanyname());
                                companyInfo.setMoney(object.get(i).getMoney());
                                companyInfo.setType(object.get(i).getType());
                                companyInfo.setJobname(object.get(i).getJobname());
                                companyInfo.setEducation(object.get(i).getEducation());
                                companyInfo.setDescribe(object.get(i).getDescribe());
                                mList.add(companyInfo);
                            }
                            searchRecyclerViewAdapter.notifyDataSetChanged();
                        } else {
                            Log.e("BMOB", e.toString());
                            Toast.makeText(SearchActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
            BmobQuery<CompanyInfo> categoryBmobQuery1 = new BmobQuery<>();
            categoryBmobQuery1.addWhereEqualTo("worktime", mSearchHeaderTv.getText().toString().trim());
            categoryBmobQuery1.findObjects(new FindListener<CompanyInfo>() {
                @Override
                public void done(List<CompanyInfo> object, BmobException e) {
                    if (object.size() != 0) {
                        if (e == null) {
                            Toast.makeText(SearchActivity.this, "查询成功：", Toast.LENGTH_LONG).show();
                            for (int i = 0; i < object.size(); i++) {
                                CompanyInfo companyInfo = new CompanyInfo();
                                companyInfo.setUsername(object.get(i).getUsername());
                                companyInfo.setAddress(object.get(i).getAddress());
                                companyInfo.setWorktime(object.get(i).getWorktime());
                                companyInfo.setWorkexperience(object.get(i).getWorkexperience());
                                companyInfo.setCompanyname(object.get(i).getCompanyname());
                                companyInfo.setMoney(object.get(i).getMoney());
                                companyInfo.setType(object.get(i).getType());
                                companyInfo.setJobname(object.get(i).getJobname());
                                companyInfo.setEducation(object.get(i).getEducation());
                                companyInfo.setDescribe(object.get(i).getDescribe());
                                mList.add(companyInfo);
                            }
                            searchRecyclerViewAdapter.notifyDataSetChanged();
                        } else {
                            Log.e("BMOB", e.toString());
                            Toast.makeText(SearchActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
            BmobQuery<CompanyInfo> categoryBmobQuery2 = new BmobQuery<>();
            categoryBmobQuery2.addWhereEqualTo("type", mSearchHeaderTv.getText().toString().trim());
            categoryBmobQuery2.findObjects(new FindListener<CompanyInfo>() {
                @Override
                public void done(List<CompanyInfo> object, BmobException e) {
                    if (object.size() != 0) {
                        if (e == null) {
                            Toast.makeText(SearchActivity.this, "查询成功：", Toast.LENGTH_LONG).show();
                            for (int i = 0; i < object.size(); i++) {
                                CompanyInfo companyInfo = new CompanyInfo();
                                companyInfo.setUsername(object.get(i).getUsername());
                                companyInfo.setAddress(object.get(i).getAddress());
                                companyInfo.setWorktime(object.get(i).getWorktime());
                                companyInfo.setWorkexperience(object.get(i).getWorkexperience());
                                companyInfo.setCompanyname(object.get(i).getCompanyname());
                                companyInfo.setMoney(object.get(i).getMoney());
                                companyInfo.setType(object.get(i).getType());
                                companyInfo.setJobname(object.get(i).getJobname());
                                companyInfo.setEducation(object.get(i).getEducation());
                                companyInfo.setDescribe(object.get(i).getDescribe());
                                mList.add(companyInfo);
                            }
                            searchRecyclerViewAdapter.notifyDataSetChanged();
                        } else {
                            Log.e("BMOB", e.toString());
                            Toast.makeText(SearchActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
            BmobQuery<CompanyInfo> categoryBmobQuery3 = new BmobQuery<>();
            categoryBmobQuery3.addWhereEqualTo("username", mSearchHeaderTv.getText().toString().trim());
            categoryBmobQuery3.findObjects(new FindListener<CompanyInfo>() {
                @Override
                public void done(List<CompanyInfo> object, BmobException e) {
                    if (object.size() != 0) {
                        if (e == null) {
                            Toast.makeText(SearchActivity.this, "查询成功：", Toast.LENGTH_LONG).show();
                            for (int i = 0; i < object.size(); i++) {
                                CompanyInfo companyInfo = new CompanyInfo();
                                companyInfo.setUsername(object.get(i).getUsername());
                                companyInfo.setAddress(object.get(i).getAddress());
                                companyInfo.setWorktime(object.get(i).getWorktime());
                                companyInfo.setWorkexperience(object.get(i).getWorkexperience());
                                companyInfo.setCompanyname(object.get(i).getCompanyname());
                                companyInfo.setMoney(object.get(i).getMoney());
                                companyInfo.setType(object.get(i).getType());
                                companyInfo.setJobname(object.get(i).getJobname());
                                companyInfo.setEducation(object.get(i).getEducation());
                                companyInfo.setDescribe(object.get(i).getDescribe());
                                mList.add(companyInfo);
                            }
                            searchRecyclerViewAdapter.notifyDataSetChanged();
                        } else {
                            Log.e("BMOB", e.toString());
                            Toast.makeText(SearchActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });

        }
    }


    private void init() {
        // 初始化搜索历史
        mSearchHistoryLists = new ArrayList<>();
        // 初始化存储 搜索历史集合 的工具类
        mStorageListSPUtils = new StorageListSPUtils(this, TAG);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    //设置监听器
    private void initListener() {
        mSearchHeaderTv.setOnEditorActionListener(this);
        textView2.setOnClickListener(this);
        mSearchDeleteHistory.setOnClickListener(this);
        mSearchHeaderTv.addTextChangedListener(textWatcher);
        imageView.setOnClickListener(this);
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (mSearchHeaderTv.getEditableText().length() >= 1) {
                imageView.setVisibility(View.VISIBLE);
            } else {
                imageView.setVisibility(View.GONE);
            }
            mList.removeAll(mList);
            processAction();
        }
    };

    //点击事件（清空）
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.delete:
                mSearchHeaderTv.setText("");
                break;
            case R.id.textView:
                // 存取 SharedPreferences 中存储的搜索历史并做相应的处理
                mList.removeAll(mList);
                processAction();
                break;
            case R.id.imageView9:
                // 删除搜索历史
                new AlertDialog.Builder(this)
                        .setMessage(getResources().getString(R.string.app_commit_delete_history))
                        .setCancelable(false)
                        .setPositiveButton(getResources().getString(R.string.app_delete_confirm), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 清楚 SharedPreferences 中存储的搜索历史
                                mStorageListSPUtils.removeDateList(TAG_SEARCH_HISTORY);
                                mSearchHistoryLists.clear();
                                mSearchHistoryFl.removeAllViews();
                            }
                        })
                        .setNegativeButton(getResources().getString(R.string.app_delete_cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
                break;
        }
    }

    class SearchRecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> {
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = View.inflate(SearchActivity.this, R.layout.chatlayout, null);

            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            CompanyInfo companyInfo = mList.get(position);
            holder.address.setText(companyInfo.getAddress());
            holder.companyname.setText(companyInfo.getCompanyname());
            holder.jobname.setText(companyInfo.getJobname());
            holder.education.setText(companyInfo.getEducation());
            holder.workexperience.setText(companyInfo.getWorkexperience());
            holder.content.setText(companyInfo.getDescribe());
            holder.salary.setText(companyInfo.getMoney());
            holder.worktime.setText(companyInfo.getWorktime());
            holder.jobtype.setText(companyInfo.getType());
            holder.username.setText(companyInfo.getUsername());
            //rootView控件跳转
            holder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyJobInfo myJobInfo = new MyJobInfo();

                    myJobInfo.setMyname(searchname);
                    myJobInfo.setUsername(holder.username.getText().toString());
                    myJobInfo.setCompanyname(holder.companyname.getText().toString());
                    myJobInfo.setType(holder.jobtype.getText().toString());
                    myJobInfo.setJobname(holder.jobname.getText().toString());
                    myJobInfo.setMoney(holder.salary.getText().toString());
                    myJobInfo.setWorkexperience(holder.workexperience.getText().toString());
                    myJobInfo.setEducation(holder.education.getText().toString());
                    myJobInfo.setAddress(holder.address.getText().toString());
                    myJobInfo.setWorktime(holder.worktime.getText().toString());
                    myJobInfo.setDescribe(holder.content.getText().toString());
                    myJobInfo.save(new SaveListener<String>() {
                        @Override
                        public void done(String objectId, BmobException e) {
                            if (e == null) {
                                Toast.makeText(SearchActivity.this, "添加数据成功" + objectId, Toast.LENGTH_LONG);

                            } else {
                                Toast.makeText(SearchActivity.this, "创建数据失败：" + e.getMessage(), Toast.LENGTH_LONG);
                            }
                        }
                    });


                    Intent intent = new Intent(v.getContext(), JobInfoActivity.class);
                    intent.putExtra("companyInfo", companyInfo);
                    v.getContext().startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }
    }


    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        TextView jobname;
        TextView companyname;
        TextView salary;
        TextView username;
        TextView address;
        TextView worktime;
        TextView jobtype;
        TextView education;
        TextView workexperience;
        TextView content;


        public ViewHolder(View view) {
            super(view);
            mView = view;
            jobname = view.findViewById(R.id.textView9);
            companyname = view.findViewById(R.id.textView13);
            salary = view.findViewById(R.id.textView14);
            username = view.findViewById(R.id.textView7);
            address = view.findViewById(R.id.textView8);
            worktime = view.findViewById(R.id.textView19);
            jobtype = view.findViewById(R.id.textView16);
            content = view.findViewById(R.id.textView17);
            workexperience = view.findViewById(R.id.textView18);
            education = view.findViewById(R.id.textView20);
        }
    }

}
